<template>
  <div class="panel-data">
    <div class="content">
      <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" :componentStyle="form.componentStyle" />
      <el-form
        ref="form"
        class="prop-form remote-control-button-unique"
        label-position="right"
        :model="form"
        label-width="93px"
      >
        <panel-data
          ref="panelDataCommon"
          class="remote-control-button-unique"
          :config="config"
          :widgetInstanceId="widgetInstanceId"
          :dataSourceTypeOptions="dataSourceTypeOptions"
          :dataForm="form"
          :isAurora="isAurora"
        >
          <template #dataMapping>
            <div>
              <el-table
                :data="form.tableData"
                style="width: 100%"
                size="default"
                class="mapping-table"
                :tooltip-effect="xvueTheme"
              >
                <!-- 序号 -->
                <el-table-column type="index" :label="$demoi18n('panel.th.number')" :width="55"></el-table-column>

                <!-- 属性名称 -->
                <el-table-column
                  prop="name"
                  :label="$demoi18n('panel.tab.property')"
                  width="130"
                  :show-overflow-tooltip="true"
                  :show-tooltip-when-overflow="true"
                >
                  <template #default="scope">
                    <span v-if="!scope.row.skipVerification" class="mapping-scope">
                      *
                    </span>
                    <span> {{ scope.row.name }}</span>
                  </template>
                </el-table-column>

                <!-- 属性值 -->
                <el-table-column label="属性值" min-width="70" :render-header="renderTableHeader">
                  <template #default="scope">
                    <VsFormItem
                      :prop="`tableData[${scope.$index}]`"
                      :rules="!scope.row.skipVerification ? valueRules : { required: false }"
                    >
                      <el-input v-model="scope.row.value" size="default"> </el-input>
                    </VsFormItem>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="isOpenCtrol"
                  prop="type"
                  label="开度值"
                  min-width="36"
                  :render-header="renderTableHeader"
                  :show-overflow-tooltip="true"
                  :show-tooltip-when-overflow="true"
                >
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.type"> </el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="isOpenSpeed"
                  prop="speedType"
                  label="速度值"
                  min-width="36"
                  :render-header="renderTableHeader"
                  :show-overflow-tooltip="true"
                  :show-tooltip-when-overflow="true"
                >
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.type"> </el-checkbox>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </panel-data>
      </el-form>
    </div>
  </div>
</template>
<script lang="jsx">
import STATIC_DATA from '@/common/staticData';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import VsFormItem from '@/components/common/vs-form-item/vs-form-item.vue';
import PanelData from '@/components/panel-data/panel-data-common';
import xTagBase from '@/components/panel-data/xtag-base.js';
import EventBus from '@/event-bus/EventBus.js';
import panelDataBase from '@/mixin/panel-data-base.js';
import dataModel from '@/models/panel-config-data.js';
import { clone } from '@/utils/util';
import { check, rcEquimentObjModelCode } from './valid.js';

export default {
  components: {
    PanelData,
    PanelLabelOverflowTooltip,
    VsFormItem,
  },
  mixins: [panelDataBase, xTagBase],
  props: ['config', 'widgetInstanceId', 'dataForm', 'dataSourceTypeOptions', 'isAurora'],
  data() {
    const form = clone(this.config.config.data);
    const isOpenCtrol = this.config.config.property.type === 'kaidu';
    const isOpenSpeed = this.config.config.property.type === 'speedControl';
    return {
      form,
      isOpenCtrol,
      isOpenSpeed,
      valueRules: { validator: check, trigger: ['blur', 'change'] },
    };
  },
  watch: {
    'form.dataSourceType': {
      handler(newVal) {
        if (newVal === 'staticData') {
          this.updateTableData([]);
        }
      },
      immediate: true,
    },
    'form.apiCode': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.updateTableData(newVal);
        }
      },
    },
    'form.tableData': {
      handler(newVal, oldVal) {
        EventBus.$emit(`update-tableData_${this.widgetInstanceId}`, newVal);
      },
      deep: true,
    },
  },
  created() {
    EventBus.$on(`changeControlType_${this.widgetInstanceId}`, this.onControlTypeChange);
  },
  methods: {
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
    combineFieldAndData(fields, record) {
      const result = [];
      const id = record.id || 0;
      Object.entries(record).forEach(([key, value]) => {
        fields.forEach(field => {
          if (field.code === key) {
            const data = {
              code: field.code,
              dataType: field.dataType,
              name: field.name,
              skipVerification: field.skipVerification,
              value,
              id,
            };
            result.push(data);
          }
        });
      });

      // 将配置里面的value覆盖当前表该字段的值
      const tabs = this.form.tableData;
      result.forEach(item => {
        tabs.forEach(inner => {
          if (item.code === inner.code) {
            item.value = inner.value;
            item.type = inner.type;
          }
        });
      });

      return result;
    },
    onControlTypeChange(type) {
      this.isOpenCtrol = type === 'kaidu';
      this.isOpenSpeed = type === 'speedControl';
      if (!this.isOpenCtrol && !this.isOpenSpeed) {
        this.form.tableData.forEach(item => (item.type = false));
      }
    },
    updateTableData(params) {
      const { dataSourceType = '' } = this.form;
      if (dataSourceType === 'xMiner') {
        this.loadFromxMiner();
      } else if (dataSourceType === 'fabric') {
        this.loadFromFrabic(params);
      } else if (dataSourceType === 'staticData') {
        this.loadStaticData();
      } else {}
    },
    loadFromxMiner() {
      const { dataSourceType, dataSource } = this.form;
      if (dataSourceType !== 'xMiner') {
        return;
      }
      this.isLoading = true;

      // 获取数据源
      dataModel[`getObjModelFieldList${dataSourceType}`](dataSource, rcEquimentObjModelCode)
        .then(fields => {
          if (fields.length) {
            const fieldsInfo = fields.map(info => {
              return {
                code: info.code,
                name: info.name,
                dataType: info.dataType,
                skipVerification: info.isRequired === false,
              };
            });

            /*
             * 请求对象模型表记录，更新记录的value到table显示
             * 暂不支持增加或删除等操作，所以只请求一条记录，默认只有一条记录，仅支持update
             */
            const params = {
              pageIndex: 1,
              pageSize: 1,
              filter: [],
              order: [{}],
            };
            const method = `getObjModelDataList${dataSourceType}`;
            dataModel[method](rcEquimentObjModelCode, params)
              .then(list => {
                const [record] = list || [];

                // 合并字段类型和当前记录该字段的值
                const res = this.combineFieldAndData(fieldsInfo, record);
                this.form.tableData = res;
              })
              .finally(() => {
                this.isLoading = false;
              });
          } else {
            this.isLoading = false;
          }
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    loadFromFrabic(_params) {
      this.isLoading = true;
      const { apiCode, dataSource } = this.form;
      const method = `getMappingOptions${this.form.dataSourceType}`;
      dataModel[method](apiCode)
        .then(({ list, redisKey, params = [] }) => {
          this.insertRedisKey(this.form, redisKey);
          const tabs = this.form.tableData;
          const res = [];

          params.forEach(item => {
            if (!item.name) {
              item.name = item.code;
            }

            if (item.value === undefined) {
              item.value = '';
            }

            // 只取需要的参数，避免保存配置时参数校验失败
            const param = {
              apiCode: item.apiCode,
              code: item.code,
              name: item.name,
              value: item.value,
              dataType: item.dataType,
              skipVerification: item.skipVerification || false,
            };
            tabs.forEach(tab => {
              if (param.code === tab.code) {
                param.value = tab.value;
                param.type = tab.type;
              }
            });
            res.push(param);
          });
          this.form.tableData = res;
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    loadStaticData() {
      const data = STATIC_DATA[this.config.propertyPannelName];
      this.form.tableData = data;
    },
  },
};
</script>
